{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "184878ec-80c1-4533-a7f8-f7fecbc3d8ad",
   "metadata": {},
   "source": [
    "# Build a RAG using a locally hosted NIM\n",
    "\n",
    "This notebook demonstrates how to build a RAG using NVIDIA NIM microservices. We locally host a Llama3-8b-instruct model using [NVIDIA NIM for LLMs](https://docs.nvidia.com/nim/large-language-models/latest/introduction.html) and connect to it using [LangChain NVIDIA AI Endpoints](https://python.langchain.com/docs/integrations/chat/nvidia_ai_endpoints/) package.\n",
    "\n",
    "We then create a vector store by downloading web pages and generating their embeddings using FAISS. We then showcase two different chat chains for querying the vector store. For this example, we use the NVIDIA Triton documentation website, though the code can be easily modified to use any other source. For the embedding model, we use [the GPU accelerated NV-Embed-QA model from NVIDIA API Catalog](https://build.nvidia.com/nvidia/embed-qa-4).\n",
    "\n",
    "### First stage is to load NVIDIA Triton documentation from the web, chunkify the data, and generate embeddings using FAISS\n",
    "\n",
    "To get started:\n",
    "\n",
    "1. Generate an [NGC CLI API key] On build.nvidia.com. This key will need to be passed to docker run in the next section as the NGC_API_KEY environment variable to download the appropriate models and resources when starting the NIM."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "225c7185",
   "metadata": {},
   "source": [
    "Note: In order to run this notebook, you need to launch the NIM Docker container in the terminal outside of the web browser notebook environment. Run the commands in the first 3 cells from a terminal then begin with the 4th cell (curl inference command) within the notebook environment (web browser)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19a7e489",
   "metadata": {},
   "source": [
    "Launch the NIM LLM microservice by executing this command from the terminal where you have exported all the environment variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88f612dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "# Stop and remove existing container\n",
    "docker stop meta-llama3-8b-instruct || true\n",
    "docker rm meta-llama3-8b-instruct || true\n",
    "\n",
    "NGC_API_KEY=\"NVIDIA_API_KEY\"\n",
    "\n",
    "echo \"${NGC_API_KEY}\" | docker login nvcr.io -u \"\\$oauthtoken\" --password-stdin\n",
    "\n",
    "# Create and set permissions for cache directories\n",
    "mkdir -p $HOME/.nim-cache\n",
    "chmod -R 777 $HOME/.nim-cache\n",
    "\n",
    "# Start container\n",
    "docker run -d \\\n",
    "    --name meta-llama3-8b-instruct \\\n",
    "    --gpus all \\\n",
    "    --shm-size=16GB \\\n",
    "    -e NGC_API_KEY=\"${NGC_API_KEY}\" \\\n",
    "    -v $HOME/.nim-cache:/opt/nim/.cache \\\n",
    "    --user root \\\n",
    "    --network=container:verb-workspace \\\n",
    "    nvcr.io/nim/meta/llama3-8b-instruct:1.0.0\n",
    "\n",
    "echo \"Container started, waiting for service to be ready...\"\n",
    "\n",
    "# Loop until the service is ready\n",
    "max_attempts=30\n",
    "attempt=0\n",
    "while [ $attempt -lt $max_attempts ]; do\n",
    "    if curl -s http://localhost:8000/v1/health/ready > /dev/null; then\n",
    "        echo \"Service is ready!\"\n",
    "        break\n",
    "    else\n",
    "        attempt=$((attempt + 1))\n",
    "        echo \"Attempt $attempt/$max_attempts: Service not ready yet, waiting...\"\n",
    "        sleep 10\n",
    "    fi\n",
    "done\n",
    "\n",
    "if [ $attempt -eq $max_attempts ]; then\n",
    "    echo \"Service failed to become ready after $max_attempts attempts\"\n",
    "    docker logs meta-llama3-8b-instruct\n",
    "    exit 1\n",
    "fi"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37e2fcda",
   "metadata": {},
   "source": [
    "Before we continue and connect the NIM to LangChain, let's test it using a simple OpenAI completion request. You can execute this command and all the subsequent one after this from your web browser."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "af3bf04b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"id\":\"cmpl-7b43d98dc1264bfd9b5b57a88bc98114\",\"object\":\"text_completion\",\"created\":1734035097,\"model\":\"meta/llama3-8b-instruct\",\"choices\":[{\"index\":0,\"text\":\", in a small village nestled in the rolling hills of the countryside, there lived a young girl named Sophie. Sophie was a curious and adventurous child, with a mop of curly brown hair and a smile that could light up a room. She loved to explore the world around her, and was constantly asking questions about the mysteries\",\"logprobs\":null,\"finish_reason\":\"length\",\"stop_reason\":null}],\"usage\":{\"prompt_tokens\":5,\"total_tokens\":69,\"completion_tokens\":64}}"
     ]
    }
   ],
   "source": [
    "!curl -X 'POST' \\\n",
    "    \"http://0.0.0.0:8000/v1/completions\" \\\n",
    "    -H \"accept: application/json\" \\\n",
    "    -H \"Content-Type: application/json\" \\\n",
    "    -d '{\"model\": \"meta/llama3-8b-instruct\", \"prompt\": \"Once upon a time\", \"max_tokens\": 64}'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79c2aa6f",
   "metadata": {},
   "source": [
    "Now setup the LangChain flow by installing prerequisite libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5966ea5a",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip uninstall -y langchain langchain-nvidia-ai-endpoints langchain-core langchain-community langchain-text-splitters langsmith\n",
    "!pip install --upgrade pip\n",
    "!pip install langchain\n",
    "!pip install langchain-nvidia-ai-endpoints\n",
    "!pip install faiss-gpu\n",
    "!pip install -U langchain-community"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74b0c989",
   "metadata": {},
   "source": [
    "Set up NVIDIA API key, which you can get from the [API Catalog](https://build.nvidia.com/). This key will be used to communicate with GPU accelerated cloud hosted embedding model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79771ce9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "if not os.environ.get(\"NVIDIA_API_KEY\", \"\").startswith(\"nvapi-\"):\n",
    "    nvapi_key = getpass.getpass(\"Enter your NVIDIA API key: \")\n",
    "    assert nvapi_key.startswith(\"nvapi-\"), f\"{nvapi_key[:5]}... is not a valid key\"\n",
    "    os.environ[\"NVIDIA_API_KEY\"] = nvapi_key"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5584e3b1",
   "metadata": {},
   "source": [
    "We can now connect with the deployed NIM LLM model in LangChain by specifying the base URL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35baa8c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_nvidia_ai_endpoints import ChatNVIDIA\n",
    "\n",
    "llm = ChatNVIDIA(base_url=\"http://0.0.0.0:8000/v1\", model=\"meta/llama3-8b-instruct\", temperature=0.1, max_tokens=1000, top_p=1.0)\n",
    "\n",
    "result = llm.invoke(\"What is the capital of France?\")\n",
    "print(result.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f95b2753",
   "metadata": {},
   "source": [
    "Import all the required libraries for building the langchain agent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "42bf2619-1ca3-4477-82b8-88c240dd87ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from langchain.chains import ConversationalRetrievalChain, LLMChain\n",
    "from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT, QA_PROMPT\n",
    "from langchain.chains.question_answering import load_qa_chain\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "from langchain.vectorstores import FAISS\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_nvidia_ai_endpoints import ChatNVIDIA\n",
    "from langchain_nvidia_ai_endpoints import NVIDIAEmbeddings"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "eb7f8822",
   "metadata": {},
   "source": [
    "Helper functions for loading html files, which we'll use to generate the embeddings. We'll use this later to load the relevant html documents from the Triton documentation website and convert to a vector store."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "f8097819",
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "from typing import List, Union\n",
    "\n",
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "\n",
    "def html_document_loader(url: Union[str, bytes]) -> str:\n",
    "    \"\"\"\n",
    "    Loads the HTML content of a document from a given URL and return it's content.\n",
    "\n",
    "    Args:\n",
    "        url: The URL of the document.\n",
    "\n",
    "    Returns:\n",
    "        The content of the document.\n",
    "\n",
    "    Raises:\n",
    "        Exception: If there is an error while making the HTTP request.\n",
    "\n",
    "    \"\"\"\n",
    "    try:\n",
    "        response = requests.get(url)\n",
    "        html_content = response.text\n",
    "    except Exception as e:\n",
    "        print(f\"Failed to load {url} due to exception {e}\")\n",
    "        return \"\"\n",
    "\n",
    "    try:\n",
    "        # Create a Beautiful Soup object to parse html\n",
    "        soup = BeautifulSoup(html_content, \"html.parser\")\n",
    "\n",
    "        # Remove script and style tags\n",
    "        for script in soup([\"script\", \"style\"]):\n",
    "            script.extract()\n",
    "\n",
    "        # Get the plain text from the HTML document\n",
    "        text = soup.get_text()\n",
    "\n",
    "        # Remove excess whitespace and newlines\n",
    "        text = re.sub(\"\\s+\", \" \", text).strip()\n",
    "\n",
    "        return text\n",
    "    except Exception as e:\n",
    "        print(f\"Exception {e} while loading document\")\n",
    "        return \"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b6a2d1e0",
   "metadata": {},
   "source": [
    "Read html files and split text in preparation for embedding generation\n",
    "Note chunk_size value must match the specific LLM used for embedding genetation\n",
    "\n",
    "Make sure to pay attention to the chunk_size parameter in TextSplitter. Setting the right chunk size is critical for RAG performance, as much of a RAG’s success is based on the retrieval step finding the right context for generation. The entire prompt (retrieved chunks + user query) must fit within the LLM’s context window. Therefore, you should not specify chunk sizes too big, and balance them out with the estimated query size. For example, while OpenAI LLMs have a context window of 8k-32k tokens, Llama3 is limited to 8k tokens. Experiment with different chunk sizes, but typical values should be 100-600, depending on the LLM."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "56aa8900",
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_embeddings(embedding_path: str = \"./data/nv_embedding\"):\n",
    "\n",
    "    embedding_path = \"./data/nv_embedding\"\n",
    "    print(f\"Storing embeddings to {embedding_path}\")\n",
    "\n",
    "    # List of web pages containing NVIDIA Triton technical documentation\n",
    "    urls = [\n",
    "         \"https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/index.html\",\n",
    "         \"https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/getting_started/quickstart.html\",\n",
    "         \"https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/user_guide/model_repository.html\",\n",
    "         \"https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/user_guide/model_analyzer.html\",\n",
    "         \"https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/user_guide/architecture.html\",\n",
    "    ]\n",
    "\n",
    "\n",
    "    documents = []\n",
    "    for url in urls:\n",
    "        document = html_document_loader(url)\n",
    "        documents.append(document)\n",
    "\n",
    "\n",
    "    text_splitter = RecursiveCharacterTextSplitter(\n",
    "        chunk_size=1000,\n",
    "        chunk_overlap=0,\n",
    "        length_function=len,\n",
    "    )\n",
    "    texts = text_splitter.create_documents(documents)\n",
    "    index_docs(url, text_splitter, texts, embedding_path)\n",
    "    print(\"Generated embedding successfully\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4d4e2097",
   "metadata": {},
   "source": [
    "Generate embeddings using NVIDIA Retrieval QA Embedding NIM and NVIDIA AI Endpoints for LangChain and save embeddings to offline vector store in the /embed directory for future re-use"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "fc7e6a93",
   "metadata": {},
   "outputs": [],
   "source": [
    "def index_docs(url: Union[str, bytes], splitter, documents: List[str], dest_embed_dir) -> None:\n",
    "    \"\"\"\n",
    "    Split the document into chunks and create embeddings for the document\n",
    "\n",
    "    Args:\n",
    "        url: Source url for the document.\n",
    "        splitter: Splitter used to split the document\n",
    "        documents: list of documents whose embeddings needs to be created\n",
    "        dest_embed_dir: destination directory for embeddings\n",
    "\n",
    "    Returns:\n",
    "        None\n",
    "    \"\"\"\n",
    "    embeddings = NVIDIAEmbeddings(model=\"NV-Embed-QA\", truncate=\"END\")\n",
    "\n",
    "    for document in documents:\n",
    "        texts = splitter.split_text(document.page_content)\n",
    "\n",
    "        # metadata to attach to document\n",
    "        metadatas = [document.metadata]\n",
    "\n",
    "        # create embeddings and add to vector store\n",
    "        if os.path.exists(dest_embed_dir):\n",
    "            update = FAISS.load_local(folder_path=dest_embed_dir, embeddings=embeddings, allow_dangerous_deserialization=True)\n",
    "            update.add_texts(texts, metadatas=metadatas)\n",
    "            update.save_local(folder_path=dest_embed_dir)\n",
    "        else:\n",
    "            docsearch = FAISS.from_texts(texts, embedding=embeddings, metadatas=metadatas)\n",
    "            docsearch.save_local(folder_path=dest_embed_dir)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "44650d71",
   "metadata": {},
   "source": [
    "### Second stage is to load the embeddings from the vector store and build a RAG using NVIDIAEmbeddings\n",
    "\n",
    "Create the embeddings model using NVIDIA Retrieval QA Embedding NIM from the API Catalog. This model represents words, phrases, or other entities as vectors of numbers and understands the relation between words and phrases. See here for reference: https://build.nvidia.com/nvidia/embed-qa-4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "10db1c5c-f515-460f-bf23-5d68f195e52b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Storing embeddings to ./data/nv_embedding\n",
      "Generated embedding successfully\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "create_embeddings()\n",
    "\n",
    "embedding_model = NVIDIAEmbeddings(model=\"NV-Embed-QA\", truncate=\"END\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73f9f5e2",
   "metadata": {},
   "source": [
    "Load documents from vector database using FAISS"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "d55bb79e-5bb6-409d-8ead-3c3006aeb2ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Embed documents\n",
    "embedding_path = \"./data/nv_embedding\"\n",
    "docsearch = FAISS.load_local(folder_path=embedding_path, embeddings=embedding_model, allow_dangerous_deserialization=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7614e948-aab6-40d5-bf14-4f8ba99b1329",
   "metadata": {},
   "source": [
    "Create a ConversationalRetrievalChain chain using a local NIM. We'll use the Llama3 8B NIM we created and deployed locally, add memory for chat history, and connect to the vector store via the embedding model. See here for reference: https://python.langchain.com/docs/modules/chains/popular/chat_vector_db#conversationalretrievalchain-with-streaming-to-stdout"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "94b49b4a",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = ChatNVIDIA(base_url=\"http://0.0.0.0:8000/v1\", model=\"meta/llama3-8b-instruct\", temperature=0.1, max_tokens=1000, top_p=1.0)\n",
    "\n",
    "memory = ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True)\n",
    "\n",
    "qa_prompt=QA_PROMPT\n",
    "\n",
    "doc_chain = load_qa_chain(llm, chain_type=\"stuff\", prompt=QA_PROMPT)\n",
    "\n",
    "qa = ConversationalRetrievalChain.from_llm(\n",
    "    llm=llm,\n",
    "    retriever=docsearch.as_retriever(),\n",
    "    chain_type=\"stuff\",\n",
    "    memory=memory,\n",
    "    combine_docs_chain_kwargs={'prompt': qa_prompt},\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f60f2240",
   "metadata": {},
   "source": [
    "Now try asking a question about Triton with the simpler chain. Compare the answer to the result with previous complex chain model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9add6e2e",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"What is Triton?\"\n",
    "result = qa({\"question\": query})\n",
    "print(result.get(\"answer\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43b1cddd",
   "metadata": {},
   "source": [
    "Ask another question about Triton"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62654a9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"Does Triton support ONNX?\"\n",
    "result = qa({\"question\": query})\n",
    "print(result.get(\"answer\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f178ac86",
   "metadata": {},
   "source": [
    "Finally showcase chat capabilites by asking a question about the previous query"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "781e058e",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"But why?\"\n",
    "result = qa({\"question\": query})\n",
    "print(result.get(\"answer\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a17cc4e5-2877-4229-9895-6b509eb02794",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
